package com.ebt.m.widget.indemnify.tablechart;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.ebt.m.R;
import com.ebt.m.widget.indemnify.IndemnifyConfig;
import com.ebt.m.widget.indemnify.ResourceUtil;

public class TableHead extends TableLayout {
	/** 列数 */
	private int columnSize = 0;
	/** 列数据 */
	private Object[] rowData = null;
	/** 单元格视图 */
	private View[] cellView = null;
	private LayoutInflater inflater;
	private Context context;
	private IndemnifyConfig config;
	private TableRow headRow;
	private boolean hasMeasured = false;
	private ViewTreeObserver viewTreeObserver;
	private ViewTreeObserver.OnPreDrawListener onPreDrawListener = new ViewTreeObserver.OnPreDrawListener() {
		public boolean onPreDraw() {
			if (hasMeasured == false) {
				hasMeasured = true;
				setStretchable();
			}
			return true;
		}
	};
	private CellOnClickListener mElementOnClickListener = new CellOnClickListener();

	public TableHead(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		headRow = (TableRow) inflater.inflate(R.layout.table_head_row, null);// null:返回xml根view
		this.addView(headRow);// 添加行视图
		headRow.removeAllViews();
	}

	/**
	 * 初始化数据
	 * 
	 * @param config
	 */
	public void setConfig(IndemnifyConfig config) {
		this.config = config;
		initData();
		initRowView();
	}

	/**
	 * 初始化数据
	 */
	private void initData() {
		rowData = config.getTitles();
		columnSize = rowData.length;
		cellView = new View[2];
	}

	public void initRowView() {

		// 添加保单年度列
		cellView[0] = (TextView) inflater.inflate(ResourceUtil.getLayoutId(context, "table_head_cell1"), headRow, false);
		((TextView) cellView[0]).setText(getResources().getString(R.string.insurance_year));
		headRow.addView(cellView[0]);
		// 添加年末年龄列
		cellView[0] = (TextView) inflater.inflate(ResourceUtil.getLayoutId(context, "table_head_cell1"), headRow, false);
		((TextView) cellView[0]).setText(getResources().getString(R.string.year_end_age));

		TableRow.LayoutParams params = (TableRow.LayoutParams) cellView[0].getLayoutParams();
		params.leftMargin = 0;
		cellView[0].setLayoutParams(params);
		headRow.addView(cellView[0]);

		createItems();

		viewTreeObserver = this.getViewTreeObserver();
		// 绘制视图之前回调接口
		viewTreeObserver.addOnPreDrawListener(onPreDrawListener);

	}

	private void createItems() {

		for (int i = 0; i < columnSize; i++) {
			cellView[1] = (TextView) inflater.inflate(ResourceUtil.getLayoutId(context, "table_head_cell2"), headRow, false);
			((TextView) cellView[1]).setText((String) rowData[i]);
			headRow.addView(cellView[1]);

			// 表格头部点击事件
			// cellView[1].setOnClickListener(mElementOnClickListener);
		}
	}

	/**
	 * 单元格点击事件
	 * 
	 * @author Allen.li
	 *
	 */
	public class CellOnClickListener implements OnClickListener {
		private TextView current = null;

		@Override
		public void onClick(View v) {
			if (current != null) {
				current.setBackgroundColor(Color.rgb(144, 148, 155));
			}
			current = (TextView) v;
			current.setBackgroundColor(context.getResources().getColor(R.color.list_item_focused));
			// Toast.makeText(context, "  " + current.getText(),
			// Toast.LENGTH_SHORT).show();
			// 清除TableBody原先选中的列，选中当前列
			config.getItemOnSelectedListener().OnSelected(findIndex(current.getText()));

		}

		private int findIndex(CharSequence charSequence) {
			for (int i = 0; i < rowData.length; i++) {
				if (((String) rowData[i]).equals(charSequence.toString())) {
					return i;
				}
			}
			return -1;
		}

		/**
		 * 设置标题是否选中,当标题选中时，调用回调函数选中列并设置声音面板
		 * 
		 * @param select
		 * @param index
		 */
		public void setTitleSelected(boolean select, int index) {
			if (select) {
				if (current != null) {
					current.setBackgroundColor(Color.rgb(144, 148, 155));
				}
				current = (TextView) headRow.getChildAt(index);
				current.setBackgroundColor(context.getResources().getColor(R.color.list_item_focused));
				// Toast.makeText(context, "  " + current.getText(),
				// Toast.LENGTH_SHORT).show();
				config.getItemOnSelectedListener().OnSelected(findIndex(current.getText()));
			} else {
				if (current != null) {
					current.setBackgroundColor(Color.rgb(144, 148, 155));
				}
			}
		}

		/**
		 * 将选中的表格头部颜色重置
		 */
		public void resetTitleSelected() {
			if (current != null) {
				current.setBackgroundColor(Color.rgb(144, 148, 155));
			}
		}
	}

	/**
	 * 重新计算宽高
	 */
	private void setStretchable() {
		// int fatherHeight = headRow.getMeasuredHeight();
		int fatherWidth = headRow.getMeasuredWidth();

		TextView firstTV = (TextView) headRow.getChildAt(0);
		TableRow.LayoutParams params = (TableRow.LayoutParams) firstTV.getLayoutParams();
		int leftMargin = params.leftMargin;
		int rightMargin = params.rightMargin;
		int width = params.width;
		int firstWidth = leftMargin + rightMargin + width;// 首项的宽

		TextView secondTV = (TextView) headRow.getChildAt(1);
		params = (TableRow.LayoutParams) secondTV.getLayoutParams();
		leftMargin = params.leftMargin;
		rightMargin = params.rightMargin;
		width = params.width;
		int secondWidth = leftMargin + rightMargin + width;// 首项的宽

		int count = headRow.getChildCount();
		int itemWidth = (int) Math.round((fatherWidth - firstWidth - secondWidth + 0.0) / (count - 2));// 重新计算之后项的宽，包含边距
		Log.i("my", "  firstWidth=" + firstWidth + ", count = " + count + ", itemWidth=" + itemWidth);
		for (int i = 2; i < count; i++) {
			TextView temp = (TextView) headRow.getChildAt(i);
			TableRow.LayoutParams paramsT = (TableRow.LayoutParams) temp.getLayoutParams();
			int leftMarginT = paramsT.leftMargin;
			int rightMarginT = paramsT.rightMargin;
			paramsT.width = itemWidth - leftMarginT - rightMarginT;
			temp.setLayoutParams(paramsT);// 一定要重新赋回去，否则会出现时而正常时而不正常的情况
		}

		// int count = headRow.getChildCount();
		// Log.i("my", "count = " + count);
		// for (int i = 0; i < count; i++) {
		// tableLayout.setColumnStretchable(i, true);
		// }
		// tableLayout.setColumnStretchable(0, false);
		// // tableLayout.setStretchAllColumns(true);
		// int w = tableLayout.getLayoutParams().width;
		// Log.i("my", "w   =" + w);

	}

	public CellOnClickListener getmElementOnClickListener() {
		return mElementOnClickListener;
	}

	public void setmElementOnClickListener(CellOnClickListener mElementOnClickListener) {
		this.mElementOnClickListener = mElementOnClickListener;
	}

	/**
	 * 隐藏最左边的一列
	 */
	public void hideLeftColumn() {
		if (headRow != null && headRow.getChildCount() > 2) {
			TextView tv = (TextView) headRow.getChildAt(1);
			tv.setVisibility(View.GONE);
		}

	}

	public void showLeftColumn() {
		if (headRow != null && headRow.getChildCount() > 2) {
			TextView tv = (TextView) headRow.getChildAt(1);
			tv.setVisibility(View.VISIBLE);
		}
	}

	public IndemnifyConfig getConfig() {
		return config;
	}

	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public int dip2px(Context context, float dpValue) {
		DisplayMetrics metrics = context.getResources().getDisplayMetrics();
		return (int) (dpValue * metrics.density + 0.5f);
	}

}
